#!/bin/sh

# Slackware build script for Cfengine
#
# Written by Menno Duursma <druiloor@zonnet.nl>

# Exit on most errors
set -e

PRGNAM=cfengine
VERSION=2.1.22
ARCH=${ARCH:-i486}
BUILD=${BUILD:-1}
TAG=${TAG:-_SBo}
CWD=$(pwd)
TMP=${TMP:-/tmp/SBo}
PKG=$TMP/package-$PRGNAM
OUTPUT=${OUTPUT:-/tmp}

if [ "$ARCH" = "i486" ]; then
  SLKCFLAGS="-O2 -march=i486 -mtune=i686"
elif [ "$ARCH" = "i686" ]; then
  SLKCFLAGS="-O2 -march=i686 -mtune=i686"
fi

rm -rf $PKG
mkdir -p $TMP $PKG $OUTPUT
cd $TMP
rm -rf $PRGNAM-$VERSION
tar -xzvf $CWD/$PRGNAM-$VERSION.tar.gz
cd $PRGNAM-$VERSION
chown -R root:root . 
chmod -R u+w,go+r-w,a-s .

# The system expects everything to live in /var/cfengine generally
# Its configuration is maintained in a version control system
CFLAGS="$SLKCFLAGS" \
CXXFLAGS="$SLKCFLAGS" \
./configure \
  --bindir=/usr/bin \
  --sbindir=/usr/sbin \
  --mandir=/usr/man \
  --infodir=/usr/info \
  --datadir=/usr/doc \
  --with-docs

# Compile the application and install it into the $PKG directory
make
make install-strip DESTDIR=$PKG

# Create the server directory (may not be needed)
mkdir -p $PKG/var/cfengine/masterfiles

# Include an example config files
mkdir -p $PKG/etc/rc.d
cat $CWD/rc.cfengine > $PKG/etc/rc.d/rc.cfengine.new
mkdir -p $PKG/var/cfengine/inputs
cat $CWD/config/update.conf > $PKG/var/cfengine/inputs/update.conf.new
cat $CWD/config/cfagent.conf > $PKG/var/cfengine/inputs/cfagent.conf.new
cat $CWD/config/cfservd.conf > $PKG/var/cfengine/inputs/cfservd.conf.new
cat $CWD/config/cfrun.hosts > $PKG/var/cfengine/inputs/cfrun.hosts.new

# Compress man pages
( cd $PKG/usr/man
  find . -type f -exec gzip -9 {} \;
  for i in $(find . -type l) ;
    do ln -s $(readlink $i).gz $i.gz ; rm $i ;
  done
)

# Compress info pages and remove the package's dir file
rm -f $PKG/usr/info/dir
gzip -9 $PKG/usr/info/*.info*
( cd $PKG/usr/info
  # link main-page to the ref doc
  ln -s cfengine-Reference.info.gz cfengine.info.gz
)

# Move program documentation into place
mv $PKG/usr/doc/$PRGNAM $PKG/usr/doc/$PRGNAM-$VERSION
( cd $PKG/usr/doc
  # Fix permissions
  find . -type f -exec chmod 644 {} \;
)

# Include the SlackBuild script in the documentation directory
cat $CWD/$PRGNAM.SlackBuild > $PKG/usr/doc/$PRGNAM-$VERSION/$PRGNAM.SlackBuild

# Copy the slack-desc (and a custom doinst.sh if necessary) into ./install
mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc
cat $CWD/doinst.sh > $PKG/install/doinst.sh

# Make the package; be sure to leave it in $OUTPUT
cd $PKG
/sbin/makepkg -l y -c n $OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD$TAG.tgz

# Clean up the extra stuff
if [ "$1" = "--cleanup" ]; then
  rm -rf $TMP/$PRGNAM-$VERSION
  rm -rf $PKG
fi

